package com.gmrz.uap.dict;


import com.gmrz.uap.cfg.SystemConst;
import com.gmrz.uap.common.ControllerSupport;
import com.gmrz.uap.common.DBCommon;
import com.gmrz.uap.jfinal.interceptor.SuperAdminAuthInterceptor;
import com.gmrz.uap.model.Dict;
import com.gmrz.uap.model.DictType;
import com.gmrz.uap.util.Identities;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.ehcache.CacheName;
import com.jfinal.plugin.ehcache.EvictInterceptor;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

public class DictController extends ControllerSupport {

    /**
     * 获取所有数据字典类型
     */
    public void findDictTypeList() {
        List<DictType> dictTypes = DictService.me.findDictTypeList();
        render(responseJsonRender(dictTypes));
    }


    public void findDictByDtID() {
        Dict dict = getModel(Dict.class);
        List<Dict> dictList = DictService.me.getDictListByDictTypeID(dict.getDtId());
        render(responseJsonRender(dictList));
    }

    @Before(SuperAdminAuthInterceptor.class)
    public void index() {
        List<DictType> dictTypes = DictService.me.findDictTypeList();
        setAttr("dictTypes", dictTypes);
    }

    public void dictList() {
        int page = getParaToInt(SystemConst.DATATABLE_PAGINATE_OFFSET, SystemConst.DATATABLE_PAGINATE_OFFSET_DEFAULT);
        int rows = getParaToInt(SystemConst.DATATABLE_PAGINATE_LIMIT, SystemConst.DATATABLE_PAGINATE_LIMIT_DEFAULT);

        String sort = getPara(SystemConst.DATATABLE_PAGINATE_SORT, DBCommon.TABLE_DICT_COLUMN_ORDER_NUMBER);
        String order = getPara(SystemConst.DATATABLE_PAGINATE_ORDER, SystemConst.DATATABLE_PAGINATE_ORDER_DEFAULT);

        Dict dict = getModel(Dict.class);

        Page<Dict> pages = DictService.me.findListPaginate(dict, page, rows, sort, order);

        result.put(SystemConst.DATATABLE_PAGINATE_TOTAL, pages.getTotalRow());
        result.put(SystemConst.DATATABLE_PAGINATE_ROWS, pages.getList());

        render(responseJsonRender(result));
    }


    public void dictTypeAdd() {
        render("dictTypeForm" + SystemConst.VIEW_EXTENDSION);
    }

    public void dictTypeSave() throws UnsupportedEncodingException {
        DictType dictType = getModel(DictType.class);

        if (null == dictType) {
            message = getRes().get("system.validator.paramnull");
            result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
            result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
            render(responseJsonRender(result));
            return;
        }


        flag = DictService.me.dictTypeExist(dictType.getDtName());
        if (!flag) {
            message = "数据字典类型已经存在";
            result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
            result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
            render(responseJsonRender(result));
            return;
        }


        dictType.setDtId(Identities.uuid2());

        flag = dictType.save();
        // 解决乱码
        String displayName = URLDecoder.decode(getPara("displayName", "字典"), "UTF-8");
        if (flag) {
            message = displayName + "增加成功！";
        } else {
            message = displayName + "增加失败！";
        }


        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }



    public void add() throws UnsupportedEncodingException {
        List<DictType> dictTypes = DictService.me.findDictTypeList();
        setAttr("dictTypes", dictTypes);

        setAttr("isDisplay", getPara("isDisplay", "1"));
        setAttr("displayName", URLDecoder.decode(getPara("displayName", "字典"), "UTF-8"));

        if (!StrKit.isBlank(getPara("dtId"))) {
            Dict dict = new Dict();
            dict.setDtId(getPara("dtId"));
            setAttr("dict", dict);
        }

        render("form" + SystemConst.VIEW_EXTENDSION);
    }


    @Before(EvictInterceptor.class)
    @CacheName("UAP_DICT_CACHE")
    public void save() throws UnsupportedEncodingException {

        Dict dict = getModel(Dict.class);

        if (null == dict) {
            message = getRes().get("system.validator.paramnull");
            result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
            result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
            render(responseJsonRender(result));
            return;
        }


        flag = DictService.me.exist(dict.getDtId(), dict.getDictName());
        if (!flag) {
            message = "数据字典已经存在";
            result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
            result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
            render(responseJsonRender(result));
            return;
        }


        dict.setDictId(Identities.uuid2());

        flag = dict.save();

        // 解决乱码
        String displayName = URLDecoder.decode(getPara("displayName", "字典"), "UTF-8");
        if (flag) {
            message = displayName + "增加成功！";
        } else {
            message = displayName + "增加失败！";
        }


        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }

    public void edit() throws UnsupportedEncodingException {
        List<DictType> dictTypes = DictService.me.findDictTypeList();
        setAttr("dictTypes", dictTypes);
        setAttr("dict", DictService.me.findById(getPara("dictId")));

        setAttr("isDisplay", getPara("isDisplay", "1"));
        setAttr("displayName", URLDecoder.decode(getPara("displayName", "字典"), "UTF-8"));


        render("form" + SystemConst.VIEW_EXTENDSION);
    }


    @Before(EvictInterceptor.class)
    @CacheName("UAP_DICT_CACHE")
    public void update() throws UnsupportedEncodingException {
        String charset = this.getRequest().getCharacterEncoding();
        String text = this.getRequest().getParameter("dict.dict_text");
        System.out.println("charset:"+charset+",text:"+text);

        Dict dict = getModel(Dict.class);

        if (null == dict) {
            message = getRes().get("system.validator.paramnull");
            result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
            result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
            render(responseJsonRender(result));
            return;
        }

        flag = dict.update();

        // 解决乱码
         String displayName = URLDecoder.decode(getPara("displayName", "字典"), "UTF-8");
        if (flag) {
            message = displayName + "编辑成功！";
        } else {
            message = displayName + "编辑失败！";
        }

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }


    public void remove() throws UnsupportedEncodingException {
        String ids = getPara("ids");
        if (StrKit.isBlank(ids)) {
            message = getRes().get("system.validator.paramnull");
            result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
            result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
            render(responseJsonRender(result));
            return;
        }


        String[] idArr = ids.split(SystemConst._DEFAULT_SEPARATOR_COMMA);
        for (String id : idArr) {
            flag = Dict.dao.deleteById(id);
            if (!flag) break;
        }

        // 解决乱码
        String displayName = URLDecoder.decode(getPara("displayName", "字典"), "UTF-8");
        if (flag) {
            message = displayName + "删除成功！";
        } else {
            message = displayName + "删除失败！";
        }

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }


    public void dict() throws UnsupportedEncodingException {
        setAttr("isDisplay", getPara("isDisplay", "1"));
        setAttr("displayName", URLDecoder.decode(getPara("displayName", "字典"), "UTF-8"));
        //System.out.println(getPara("displayName", "字典"));
        setAttr("dtId", getPara("dtId"));
    }


}
